//https://leetcode.cn/problems/spiral-matrix-ii/
package codeRandomThoughts.Test59螺旋矩阵II;

//二刷 只记得这道题是一个模拟操作的题目
public class Solution2 {
    public int[][] generateMatrix(int n) {
        //定义结果矩阵
        int[][] res = new int[n][n];
        if (n == 1) {
            res[0][0] = 1;
            return res;
        }
        //当前遍历到的坐标
        int x = 0;
        int y = 0;

        //总共要赋值n*n次
        int count = 1;
        while (count <= n * n) {
            //往右
            while (res[x][y] == 0) {
                res[x][y] = count++;
                if (y == n - 1 || res[x][y + 1] != 0) {
                    break;
                }
                y++;
            }
            x++;

            //往下
            while (res[x][y] == 0) {
                res[x][y] = count++;
                if (x == n - 1 || res[x + 1][y] != 0) {
                    break;
                }
                x++;
            }
            y--;

            //往左
            while (res[x][y] == 0) {
                res[x][y] = count++;
                if (y == 0 || res[x][y - 1] != 0) {
                    break;
                }
                y--;
            }
            x--;

            //往上
            while (res[x][y] == 0) {
                res[x][y] = count++;
                if (x == 0 || res[x - 1][y] != 0) {
                    break;
                }
                x--;
            }
            y++;
        }
        return res;
    }
}
